package server;

import net.sf.json.JSONObject;

import java.util.*;

/**
 * User: tum0r
 * Package Name: server
 * Time: 2019-03-10 Sunday 15:17:05
 */
public class VerificationCodeServer extends BaseServer {

    private String getString(int length) {
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        int n;
        char temp = 'A';
        for (int i = 0; i < length; i++) {
            n = random.nextInt(3);
            switch (n) {
                case 0:
                    temp = (char) (random.nextInt(10) + '0');
                    break;
                case 1:
                    temp = (char) (random.nextInt(10) + 'A');
                    break;
                case 2:
                    temp = (char) (random.nextInt(10) + 'a');
                    break;
            }
            if (temp != 'i' && temp != 'I' && temp != 'l' && temp != 'L' && temp != '0' && temp != 'o' && temp != 'O') {
                result.append(temp);
            } else {
                i--;
            }
        }
        return result.toString();
    }

    public String setVerificationCode(String cookie) {
        String vercode = getString(6);
        sql.update("update login set ver_code=? where cookie=?", new Object[]{vercode, cookie});
        return vercode;
    }

    public String getVerificationCode(String cookie) {
        LinkedList<LinkedHashMap<String, Object>> result = sql.query("select ver_code from login where cookie=?", new Object[]{cookie});
        if (result.size() != 0) {
            return result.get(0).get("ver_code").toString();
        }
        return "";
    }

    public String setCookie() {
        String cookie = getString(Integer.parseInt(JSONObject.fromObject(sql.query("select content from setting where name=?", new Object[]{"cookie"}).get(0).get("content").toString()).getString("cookieLength")));
        while (sql.query("select * from login where cookie=?", new Object[]{cookie}).size() != 0) {
            cookie = getString(Integer.parseInt(JSONObject.fromObject(sql.query("select content from setting where name=?", new Object[]{"cookie"}).get(0).get("content").toString()).getString("cookieLength")));
        }
        sql.update("insert into login(uuid, cookie, time) values(?, ?, ?)", new Object[]{UUID.randomUUID().toString(), cookie, new Date().getTime()});
        setVerificationCode(cookie);
        return cookie;
    }

    public boolean checkVerificationCode(String cookie, String verificationCode) {
        LinkedList<LinkedHashMap<String, Object>> temp = sql.query("select ver_code from login where cookie=?", new Object[]{cookie});
        if (temp.size() != 0) {
            return temp.get(0).get("ver_code").toString().equalsIgnoreCase(verificationCode);
        }
        return false;
    }

    public void deleteVerificationCode(String cookie) {
        sql.update("delete from login where cookie=? and user_id=''", new Object[]{cookie});
    }
}
